package com.farm.controller;

import com.alibaba.fastjson.JSONObject;
import com.farm.chat.Chat;
import com.farm.common.R;
import com.farm.util.IatTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: ChatController
 * Package: com.farm.chat
 * Description
 * @Create 2024/3/9 20:19
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Value("${pcm.basePath}")
    private String pcmPath;

    @PostMapping("/build")
    public JSONObject chatBuild(@RequestBody String question) throws InterruptedException {
        Chat chat = new Chat();
        boolean result = chat.getAccessToken();
        JSONObject jsonObject = new JSONObject();
        if (result) {
            String answer = chat.getAnswer(question);
            jsonObject.put("answer", answer);
        } else {
            jsonObject.put("answer", "网络异常");
        }
        return jsonObject;
    }

    IatTool iatTool = new IatTool("1d5d2e64");

    @PostMapping(value = "/voice",produces = "application/json; charset=UTF-8")
    public R<String> RecognizePcmfileByte(MultipartFile audioFile) {
        String question = "no idea";

        String originalFilename = audioFile.getOriginalFilename();
        // 截取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 利用uuid生成新的文件名
        String filename = UUID.randomUUID().toString() + suffix;
        // 创建文件目录
        File dir = new File(pcmPath);
        if (!dir.exists()) {
            // 文件不存在开始创建
            dir.mkdir();
        }
        // 将文件转存在本地文件中
        try {
            File oldFile = new File(pcmPath + filename);
            audioFile.transferTo(oldFile);
            String newFileName = UUID.randomUUID().toString() + suffix;
            String[] command = {
                    "ffmpeg5","-loglevel", "quiet", "-y", "-i", pcmPath + filename, "-acodec", "pcm_s16le", "-f", "s16le", "-ac", "1", "-ar", "16000", pcmPath + newFileName
            };
            // 执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.start().waitFor();
            // 等待FFmpeg命令执行完毕
            File newFile = new File(pcmPath + newFileName);
            FileInputStream fileInputStream = new FileInputStream(newFile);
            byte[] bytes = new byte[(int) newFile.length()];
            fileInputStream.read(bytes);
            question = iatTool.RecognizePcmfileByte(bytes);
            //删除两个文件
            boolean delete = oldFile.delete();
            if(delete)
                log.info("第一个文件删除成功");
            fileInputStream.close();
            boolean delete1 = newFile.delete();
            if(delete1)
                log.info("第二个文件删除成功");
            return R.success(question);
        } catch (IOException  e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return R.error("网络未知错误");
    }
}



